<template>
    <div>
        <div id="video-container" class="video-container"></div> 
    </div>
</template>

<script>
import  EZUIKit from 'ezuikit-js';
export default {
    data() {
        return {
            accessToken: null,
            expiryDate: null,
        }
    },
    mounted() {
        this.initPlayer();
        // this.initAxiosInterceptors();
    },
    methods: {  
        playVideo(){
            let _this = this; 
            console.log(_this.accessToken,"_this.accessToken");
            
            var player = new EZUIKit.EZUIKitPlayer({ 
                id: 'video-container', // 视频容器ID
                accessToken: _this.accessToken,
                url: 'ezopen://open.ys7.com/AF5990165/23.live',
            });
            player.play();
        },


        async initPlayer() {
            let _this = this;
            const token = this.getAccessToken(); 
            
            if (!token) { 
                try {
                    const response = await this.fetchAccessToken();
                    let accessToken = response.data.data.accessToken;
                    let expiryDate = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days later
                    _this.saveAccessToken(accessToken, expiryDate);
                } catch (error) {
                    console.error('Failed to fetch access token:', error);
                    return;
                }
            } 
            
            _this.playVideo();
 
        },

        async fetchAccessToken() {
            const url = "https://open.ys7.com/api/lapp/token/get";
            const data = new FormData();
            data.append('appKey', '536ef90cccf643aaad8686a9bb7a7726');
            data.append('appSecret', '780464ffacc9eef363aa95d17c835be0');

            try {
                const response = await this.$axios.post(url, data); 
                
                return response;
            } catch (error) {
                if (error.response && error.response.status === 401 && error.response.data.code === '10002') {
                    // Token 过期，尝试重新获取
                    return this.fetchAccessToken();
                }
                throw error;
            }
        },

        getAccessToken() {
            let _this = this;
            const storedToken = localStorage.getItem('accessToken');
            const storedExpiry = localStorage.getItem('expiryDate');
            _this.accessToken = storedToken;
            _this.expiryDate = storedExpiry;
            const now = new Date();

            console.log(new Date(storedExpiry),storedToken,storedExpiry);
            

            if (storedToken && storedExpiry && new Date(storedExpiry) > now) {
                return storedToken;
            }
            return null;
        },

        saveAccessToken(token, expiry) {
            localStorage.setItem('accessToken', token);
            localStorage.setItem('expiryDate', expiry.toISOString());
            this.accessToken = token;
            this.expiryDate = expiry;
        },

        initAxiosInterceptors() {
            let _this = this;
            // 请求拦截器
            _this.$axios.interceptors.request.use(config => {
                const token = this.getAccessToken();
                if (token) {
                config.headers.Authorization = `Bearer ${token}`;
                }
                return config;
            }, error => {
                return Promise.reject(error);
            });

            // 响应拦截器
            _this.$axios.interceptors.response.use(response => {
                return response;
            }, error => {
                if (error.response && error.response.status === 401 && error.response.data.code === '10002') {
                // Token 过期，尝试重新获取
                return this.fetchAccessToken().then(newToken => {
                    const originalRequest = error.config;
                    originalRequest.headers.Authorization = `Bearer ${newToken}`;
                    return _this.$axios(originalRequest);
                });
                }
                return Promise.reject(error);
            });
        },

    },
}
</script>

<style scoped>
.video-container{
    width: 100vw;
    height: 100vh;
}
</style>